<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\CommunityShare;
use Illuminate\Http\Request;

class TestController extends Controller
{
    /**
     * 测试数据库连接
     */
    public function testDatabase()
    {
        try {
            // 测试用户表
            $userCount = User::count();
            
            // 测试社区分享表
            $shareCount = CommunityShare::count();
            
            return $this->success([
                'database_connected' => true,
                'users_count' => $userCount,
                'shares_count' => $shareCount,
                'tables_exist' => [
                    'users' => true,
                    'community_shares' => true
                ]
            ], '数据库连接测试成功');
            
        } catch (\Exception $e) {
            return $this->error('数据库连接失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 测试创建分享
     */
    public function testCreateShare()
    {
        try {
            // 获取第一个用户，如果没有则创建一个测试用户
            $user = User::first();
            if (!$user) {
                $user = User::create([
                    'username' => 'testuser',
                    'email' => 'test@example.com',
                    'password' => bcrypt('password'),
                    'email_verified_at' => now()
                ]);
            }

            // 创建测试分享
            $share = CommunityShare::create([
                'user_id' => $user->id,
                'title' => '测试分享',
                'content' => '这是一个测试分享内容',
                'tags' => '测试,分享',
                'is_hidden' => false
            ]);

            $share->load('user');

            return $this->success($share, '测试分享创建成功');
            
        } catch (\Exception $e) {
            return $this->error('创建测试分享失败: ' . $e->getMessage(), 500);
        }
    }
}